//
//  LCCollectionViewLayout.m
//  UI_15_网易上面的滑动button
//
//  Created by li cheng on 16/8/3.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "LCCollectionViewLayout.h"

@interface LCCollectionViewLayout()
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *attirbutesArrray;
@property (nonatomic, assign) CGFloat itemHeight;
@property (nonatomic, assign) CGFloat contentWidth;
@end
@implementation LCCollectionViewLayout

- (instancetype)init{
    self = [super init];
    if (self) {
        _attirbutesArrray = [NSMutableArray array];
        _contentWidth = 0.0f;
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        _attirbutesArrray = [NSMutableArray array];
        _contentWidth = 0.0f;
    }
    return self;
}
// 自定义layout,必须重写的三个方法
// 计算每个item的大小
#pragma mark - 准备布局
- (void)prepareLayout{
    [super prepareLayout];
    if (_attirbutesArrray.count != 0) {
        [_attirbutesArrray removeAllObjects];
    }
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
        // 创建系统需要的布局描述类
        UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
        // 最小的起始位置
        CGFloat x = _contentWidth;
        // 宽度数组中,最小列对应的高度
        CGFloat y = 0;
        // 宽度
        CGFloat width = 0.0f;
        if ([self.delegate respondsToSelector:@selector(collectionView:layout:heightForItemAtIndexPath:)]) {
            width = [self.delegate collectionView:self.collectionView layout:self heightForItemAtIndexPath:index];
        }
        CGFloat height = 40;
        layoutAttributes.frame = CGRectMake(x, y, width, height);
        [_attirbutesArrray addObject:layoutAttributes];
        // 整个内容的最大宽度
        self.contentWidth = _contentWidth + width;
    }
}
// 返回的是, 每个item对应的布局属性
// 返回的是,每个item对应的布局属性
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    [super layoutAttributesForElementsInRect:rect];
    return _attirbutesArrray;
}
// 负责CollectionView的滚动范围
- (CGSize)collectionViewContentSize{
    [super collectionViewContentSize];
    return CGSizeMake(self.contentWidth, 0);
}
@end
